package com.cars.util.http;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import java.security.Key;
import java.security.SecureRandom;

/**
 * 加密和解密工具类
 * @author zhaoyp
 * @date 2013-11-08
 */
public class EncAndDecryptionUtil {
    /**
     * DES加密 秘钥
     */
	protected static Key key;
	/**
     * DES加解密 根据参数生成KEY
     */
	public static void setKey(String strKey){ 
	   try{  
	        KeyGenerator _generator = KeyGenerator.getInstance("DES");  
	        _generator.init(new SecureRandom(strKey.getBytes("gb2312")));  
	        key = _generator.generateKey();  
	        _generator=null;
	    }catch(Exception e){
	    	e.printStackTrace();
	    }
	}
	/**
     * DES加密 以byte[]明文输入,byte[]密文输出 
     */
	public static byte[] getEncCode(byte[] byteS){
		byte[] byteFina = null;  
		Cipher cipher;  
		try
		{
			cipher = Cipher.getInstance("DES");  
			cipher.init(Cipher.ENCRYPT_MODE,key);  
			byteFina = cipher.doFinal(byteS);
		}  
		catch(Exception e)
		{
			e.printStackTrace();
		}  
		finally
		{
			cipher = null;
		} 
		return byteFina;
	}
	/**
     * DES解密 以byte[]密文输入,以byte[]明文输出 
     */
	public static byte[] getDesCode(byte[] byteD){
		Cipher cipher;  
		byte[] byteFina=null;  
		try{
			cipher = Cipher.getInstance("DES");  
			cipher.init(Cipher.DECRYPT_MODE,key);  
			byteFina = cipher.doFinal(byteD);
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		finally
		{
			cipher=null;
		}  
		return byteFina;
	}
	private final static String DES = "DES"; 
	/** 
	* 加密 
	* @param src 数据源 
	* @param key 密钥，长度必须是8的倍数 
	* @return 返回加密后的数据 
	* @throws Exception 
	*/ 
	public static byte[] encrypt(byte[] src, byte[] key)throws Exception { 
		//DES算法要求有一个可信任的随机数源 
		SecureRandom sr = new SecureRandom(); 
		// 从原始密匙数据创建DESKeySpec对象 
		DESKeySpec dks = new DESKeySpec(key); 
		// 创建一个密匙工厂，然后用它把DESKeySpec转换成 
		// 一个SecretKey对象 
		SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES); 
		SecretKey securekey = keyFactory.generateSecret(dks); 
		// Cipher对象实际完成加密操作 
		Cipher cipher = Cipher.getInstance(DES); 
		// 用密匙初始化Cipher对象 
		cipher.init(Cipher.ENCRYPT_MODE, securekey,sr); 
		// 现在，获取数据并加密 // 正式执行加密操作 
		return cipher.doFinal(src); 
	}
	/** 
	* 解密 
	* @param src 数据源 
	* @param key 密钥，长度必须是8的倍数 
	* @return 返回解密后的原始数据 
	* @throws Exception 
	*/ 
	public static byte[] decrypt(byte[] src, byte[] key)throws Exception { 
		// DES算法要求有一个可信任的随机数源 
		SecureRandom sr = new SecureRandom(); 
		// 从原始密匙数据创建一个DESKeySpec对象 
		DESKeySpec dks = new DESKeySpec(key); 
		// 创建一个密匙工厂，然后用它把DESKeySpec对象转换成 
		// 一个SecretKey对象 
		SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES); 
		SecretKey securekey = keyFactory.generateSecret(dks); 
		// Cipher对象实际完成解密操作 
		Cipher cipher = Cipher.getInstance(DES); 
		// 用密匙初始化Cipher对象 
		cipher.init(Cipher.DECRYPT_MODE, securekey,sr); 
		// 现在，获取数据并解密 
		// 正式执行解密操作 
		return cipher.doFinal(src); 

	} 
	public static void main(String[] args) throws Exception{
		String msg = "ABCDEFGHABCDEFGHABCDEFGHABCDEFGH";
		String keyStr = "12345678";
		byte[] newMsgByte = msg.getBytes("ISO-8859-1");
		byte[] keyByte = keyStr.getBytes("gb2312");
		byte[] encByte = encrypt(newMsgByte,keyByte);
		String hex = byte2hex(encByte);
		System.out.println("hex is:"+hex);

	}
	public static String byte2hex(byte[] b) { 

        // 转成16进制字符串
        String hs = "";
        String tmp = "";
        for (int n = 0; n < b.length; n++) {

            //整数转成十六进制表示
            tmp = (Integer.toHexString(b[n] & 0xFF));
            if (tmp.length() == 1) {
                hs = hs + "0" + tmp;

            } else {
                hs = hs + tmp;
            }
        }

        tmp = null;
        return hs.toUpperCase(); //转成大写

    }

}
